package edu.purdue.cs505;

import java.util.Date;

/*
 * Class used internally to send data over the network. Capable of serializing a Message given
 * the Message and an ID for the packet. Also capable of batching messages.
 */
public class DataMessage implements Comparable<DataMessage> {
	private Message message;
	private long id;
	private long timeout;

	public DataMessage(Message message, long id) {
		this.message = message;
		this.id = id;
		this.timeout = 0;
	}

	public Message getMessage() {
		return message;
	}

	public long getId() {
		return id;
	}

	public void setTimeout(long timeFromNow) {
		timeout = new Date().getTime() + timeFromNow;
	}

	public long getTimeout() {
		return timeout;
	}

	public String serialize() {
		int[] obsoleted = message.getObsoletedMessages();
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < obsoleted.length; i++) {
			if (i > 0) {
				sb.append(",");
			}
			sb.append(Integer.toString(obsoleted[i]));
		}
		return id + Constants.SEPARATOR + message.getProcessID()
				+ Constants.SEPARATOR + sb.toString() + Constants.SEPARATOR
				+ message.getContents();
	}

	public int compareTo(DataMessage dm) {
		return -1*(int) (dm.getTimeout() - getTimeout());
	}

	@Override
	public String toString() {
		return serialize();
	}

	public static DataMessage deserialize(String message) {
		String[] parts = message.split(Constants.SEPARATOR);
		Long id = Long.parseLong(parts[0]);
		Message internalMessage = new Message();
		internalMessage.setMessageNumber(id.intValue());
		internalMessage.setProcessID(parts[1]);
		String[] obsoletedParts = parts[2].split(",");
		for (String s : obsoletedParts) {
			if (!s.equals("")) {
				internalMessage.makesObsolete(Integer.parseInt(s));
			}
		}
		internalMessage.setContents(parts[3]);
		DataMessage dm = new DataMessage(internalMessage, id.longValue());
		return dm;
	}
}
